//
//  TDAnchorController.m
//  liveDemo
//
//  Created by tuandai on 2017/4/10.
//  Copyright © 2017年 tuandai. All rights reserved.
//

#import "TDAnchorController.h"
#import "TCIMPlatform.h"
#import "TCUserInfoMgr.h"
#import "TCLiveListModel.h"
#import "TCMsgHandler.h"
#import "TCPusherMgr.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import <MediaPlayer/MediaPlayer.h>
#import "TDAnchorView.h"

@interface TDAnchorController ()<TXLivePushListener>
@property (weak, nonatomic) IBOutlet UIButton *closeBtn;

// 视频画面的父view
@property (weak, nonatomic) IBOutlet UIView *playerView;
// 是否正在播放
@property (nonatomic, assign) BOOL isplayer;
// 是否打开麦克风
@property (nonatomic, assign) BOOL isOpenMic;
// 是否打开了预览
@property (nonatomic, assign) BOOL isPreviewing;
// 是否打开了闪光灯
@property (nonatomic, assign) BOOL isFlash;
// 腾讯推流参数配置
@property (nonatomic, strong) TXLivePushConfig *txLivePushonfig;
// 直播用户信息
@property (nonatomic, strong) TCLiveInfo *liveInfo;

@property (nonatomic, strong) TXLivePush *txLivePublisher;

// 群组相关处理
@property (nonatomic, strong) AVIMMsgHandler *msgHandler;

// 主播的IM,弹幕，礼物逻辑处理View
@property (nonatomic, strong) TDAnchorView *audienceView;

@end

static NSString *pushAddress = @"rtmp://8895.livepush.myqcloud.com/live/8895_a2732b5179?bizid=8895&txSecret=ebf6aed047ae69060e0894afe87d1e3e&txTime=59172D7F";

@implementation TDAnchorController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我是主播";
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackGround:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
    
    [self playBtnClick:nil];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
#warning 分享后需要做的东西
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;    
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"我销毁了啊");
}

#pragma mark - 初始化对象
-(void)initPushObject {
    //在 _config中可以对推流的参数（如：美白，硬件加速，前后置摄像头等）做一些初始化操作，需要注意 _config不能为nil
    self.txLivePublisher = [[TXLivePush alloc] initWithConfig:self.txLivePushonfig];
    self.txLivePublisher.config = self.txLivePushonfig;
    self.audienceView.txLivePublisher = self.txLivePublisher;
    
}

#pragma mark - 创建直播聊天室
- (void)createLiveRoom {
    TCUserInfoData  *profile = [[TCUserInfoMgr sharedInstance] getUserProfile];
    self.liveInfo.userinfo.headpic = profile.faceURL;
    self.liveInfo.userinfo.nickname = profile.nickName;
    
    @weakify(self)
    NSString *groupId = @"@TGS#aRSFPCYEN";
    [self.msgHandler joinLiveRoom:nil handler:^(int errCode) {
        if (errCode == 0) {
            self.liveInfo.groupid = groupId;
            
            [[TCPusherMgr sharedInstance] getPusherUrl:profile.identifier
                                               groupId:groupId
                                                 title:self.liveInfo.title
                                              coverPic:profile.coverURL
                                              nickName:profile.nickName
                                               headPic:profile.faceURL
                                              location:self.liveInfo.userinfo.location
                                               handler:^(int errCode, NSString *pusherUrl, NSInteger timestamp) {
                                                   errCode = 0;
                                                   pusherUrl = pushAddress;
                                                   
                                                   if (errCode == 0){
                                                       
                                                       weak_self.liveInfo.playurl = pusherUrl;
                                                       
                                                       weak_self.liveInfo.timestamp = timestamp;
                                                       if (0) { // 如果有分享
                                                           
                                                       }else {
                                                           [weak_self startRtmp];
                                                       }
                                                       
                                                   }else {
                                                       [SVProgressHUD showErrorWithStatus:@"拉取直播推流地址失败"];
                                                   }
                                                   
                                                   
                                                   
                                               }];
        }else {
            [SVProgressHUD showErrorWithStatus:@"加入群组失败"];
        }

    }];
    
//    [self.msgHandler createLiveRoom:^(int errCode, NSString *groupId) {
//        if (errCode == 0) {
//            self.liveInfo.groupid = groupId;
//            
//            [[TCPusherMgr sharedInstance] getPusherUrl:profile.identifier
//                                               groupId:groupId
//                                                 title:self.liveInfo.title
//                                              coverPic:profile.coverURL
//                                              nickName:profile.nickName
//                                               headPic:profile.faceURL
//                                              location:self.liveInfo.userinfo.location
//                                               handler:^(int errCode, NSString *pusherUrl, NSInteger timestamp) {
//                                                   errCode = 0;
//                                                   pusherUrl = pushAddress;
//                                                   
//                                                   if (errCode == 0){
//                                                       
//                                                       weak_self.liveInfo.playurl = pusherUrl;
//                                                       
//                                                       weak_self.liveInfo.timestamp = timestamp;
//                                                       if (0) { // 如果有分享
//                                                           
//                                                       }else {
//                                                           [weak_self startRtmp];
//                                                       }
//                                                      
//                                                   }else {
//                                                       [SVProgressHUD showErrorWithStatus:@"拉取直播推流地址失败"];
//                                                   }
//                                                   
//                                                   
//                                                   
//                                               }];
//        }else {
//            [SVProgressHUD showErrorWithStatus:@"创建群组失败"];
//        }
//    }];
    
    
}

#pragma mark - 退出直播间
- (IBAction)exitRoom:(UIButton *)sender {
    [self.msgHandler releaseIMRef];
    [self.audienceView closeRoom];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if(_txLivePublisher != nil)
    {
        _txLivePublisher.delegate = nil;
        [_txLivePublisher stopPreview];
        _isPreviewing = NO;
        [_txLivePublisher stopPush];
        _txLivePublisher.config.pauseImg = nil;
        _txLivePublisher = nil;
    }
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];

    if (_msgHandler)
    {
        [_msgHandler deleteLiveRoom:_liveInfo.groupid handler:^(int errCode) {
            
        }];
    }
    
    [[TCPusherMgr sharedInstance] changeLiveStatus:_liveInfo.userid status:TCLiveStatus_Offline handler:^(int errCode) {
        
    }];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


#pragma mark - 开始推流了
-(BOOL)startRtmp{
    [self clearLog];
    // 判断推理链接
//    if (_rtmpUrl.length == 0) {
//        
//    }
    
//    if (!([_rtmpUrl hasPrefix:@"rtmp://"] )) {
//        [self toastTip:@"推流地址不合法，目前支持rtmp推流!"];
//        return NO;
//    }
    
    //是否有摄像头权限
    AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (statusVideo == AVAuthorizationStatusDenied) {
        [SVProgressHUD showErrorWithStatus:kErrorMsgOpenCameraFailed];
        return NO;
    }
    
    //是否有麦克风权限
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        [SVProgressHUD showErrorWithStatus:kErrorMsgOpenMicFailed];
        return NO;
    }
    

    // 往log添加版本信息
//    NSArray* ver = [TXLivePlayer getSDKVersion];
//    if ([ver count] >= 3) {
//        _logMsg = [NSString stringWithFormat:@"rtmp sdk version: %@.%@.%@",ver[0],ver[1],ver[2]];
//        [_logicView.logViewEvt setText:_logMsg];
//    }
    
    if(_txLivePublisher != nil)
    {
        _txLivePublisher.delegate = self;
        [self.txLivePublisher setVideoQuality:VIDEO_QUALITY_HIGH_DEFINITION];
        if (!_isPreviewing) {
            [_txLivePublisher startPreview:self.playerView];
            _isPreviewing = YES;
        }
        if ([_txLivePublisher startPush:pushAddress] != 0) {
            [SVProgressHUD showErrorWithStatus:@"推流器启动失败"];
            return NO;
        }
        self.audienceView.isOpenMic = YES;
        [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    }
    return YES;
}

#pragma mark - 清除聊天信息框信息
- (void)clearLog {
    
}



#pragma mark - 播放按钮
- (IBAction)playBtnClick:(UIButton *)sender {
    
    [self startPush];
    
}


#pragma 启动推流界面
- (void)startPush
{
    TCLiveInfo *publishInfo = [[TCLiveInfo alloc] init];
    publishInfo.userinfo = [[TCLiveUserInfo alloc] init];
    publishInfo.userinfo.location = @"定位";
    publishInfo.title = @"文本";
    publishInfo.userid = @"用户ID";
    // 封面图片
    //        publishInfo.userinfo.frontcoverImage = self.coverImageView.image;
    
    self.liveInfo = publishInfo;
    
    
    [self initPushObject];
    [self createLiveRoom];

    
//    [[TCIMPlatform sharedInstance] reLogin:^{
//        self.playBtn.enabled = NO;
//        TCLiveInfo *publishInfo = [[TCLiveInfo alloc] init];
//        publishInfo.userinfo = [[TCLiveUserInfo alloc] init];
//        publishInfo.userinfo.location = @"定位";
//        publishInfo.title = @"文本";
//        publishInfo.userid = @"用户ID";
//        // 封面图片
////        publishInfo.userinfo.frontcoverImage = self.coverImageView.image;
//        
//        self.liveInfo = publishInfo;
//        
//        
//        [self initPushObject];
//        [self createLiveRoom];
//        
//    } fail:^(int code, NSString *msg) {
//        NSString *err = [NSString stringWithFormat:@"%@(%d)", msg, code];
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败"
//                                                        message:err
//                                                       delegate:self
//                                              cancelButtonTitle:@"确认"
//                                              otherButtonTitles:nil];
//        [alert show];
//    }];
}

#pragma mark - 播放背景音乐
- (IBAction)musicSceneBtnClick:(UIButton *)sender {
    //创建播放器控制器
    MPMediaPickerController *mpc = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeAnyAudio];
    mpc.delegate = self;
    mpc.editing = YES;
    [self presentViewController:mpc animated:YES completion:nil];
}

#pragma mark - 前后台切换
- (void)onAppDidEnterBackGround:(UIApplication*)app {
    // 暂停背景音乐
    if (_txLivePublisher) {
        [_txLivePublisher pauseBGM];
    }
    
    if ([_txLivePublisher isPublishing]) {
        [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
            //            [_txLivePublisher resumePush];
        }];
        [_txLivePublisher pausePush];
    }
}

- (void)onAppWillEnterForeground:(UIApplication*)app {
//    if (self.liveInfo.playurl) {
//        [self startRtmp];
//  
//        return;
//    }
    // 恢复背景音乐
    if (_txLivePublisher) {
        [_txLivePublisher resumeBGM];
    }
    
    if ([_txLivePublisher isPublishing]) {
        [_txLivePublisher resumePush];
    }
}


#pragma mark - MPMediaPickerControllerDelegate
//选中后调用
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{
    NSArray *items = mediaItemCollection.items;
    MPMediaItem *item = [items objectAtIndex:0];
    
    NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
    NSLog(@"MPMediaItemPropertyAssetURL = %@", url);
    
    if (mediaPicker.editing) {
        mediaPicker.editing = NO;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.txLivePublisher stopBGM];
            // 保存url去播放
//            [self saveAssetURLToFile: url];
        });
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

//点击取消时回调
- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 推流状态变化
-(void) onPushEvent:(int)EvtID withParam:(NSDictionary*)param {
    if (EvtID == 1002) { // 开始推流
        self.isplayer = YES;
    }
//    NSLog(@"----------%d\n%@",EvtID,param);
}

// 推流画面的码率这些
-(void) onNetStatus:(NSDictionary*) param {
//    NSLog(@"----------\n%@",param);
}


#pragma mark - 懒加载
-(TXLivePushConfig *)txLivePushonfig {
    if (!_txLivePushonfig) {
        _txLivePushonfig = [[TXLivePushConfig alloc] init];
        
        _txLivePushonfig.frontCamera = YES;
        _txLivePushonfig.enableAutoBitrate = NO;
        _txLivePushonfig.videoBitratePIN = 1000;
        _txLivePushonfig.enableHWAcceleration = YES;
        
        //background push
        _txLivePushonfig.pauseFps = 10;
        _txLivePushonfig.pauseTime = 300;
        _txLivePushonfig.pauseImg = [UIImage imageNamed:@"pause_publish.jpg"];
        _txLivePushonfig.enableAEC = YES;
        _txLivePushonfig.enableNAS = YES;
        
        //耳返
        _txLivePushonfig.enableAudioPreview = YES;
    }
    return _txLivePushonfig;
}

-(AVIMMsgHandler *)msgHandler {
    if (!_msgHandler) {
        _msgHandler = [[AVIMMsgHandler alloc] init];
    }
    return _msgHandler;
}

-(TDAnchorView *)audienceView {
    if (!_audienceView) {
        _audienceView = [TDAnchorView createView];
        [self.playerView insertSubview:_audienceView atIndex:0];
        _audienceView.msgHandler = self.msgHandler;
        
        [_audienceView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.playerView);
        }];
    }
    return _audienceView;
}

@end
